package cn.net.autocode.files.pdf.search;

import cn.net.autocode.files.pdf.entity.KeyWordPosition;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.TextPosition;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PdfBoxKeyWordSearch extends PDFTextStripper {
    private PDDocument document;
    private StringBuffer keyword;
    private StringBuffer movingWords;
    private int pageNum;
    private final List<KeyWordPosition> textList;

    private PdfBoxKeyWordSearch() {
        this.document = null;
        this.movingWords = new StringBuffer();
        this.pageNum = 1;
        this.textList = new ArrayList<>();
        super.setSortByPosition(true);
    }

    public PdfBoxKeyWordSearch(PDDocument document, StringBuffer keyword, int pageNum) {
        this();
        this.document = document;
        this.keyword = new StringBuffer(keyword.toString().replaceAll("\\s", ""));
        this.pageNum = pageNum;
    }

    public List<KeyWordPosition> getKeywordPositionList() throws IOException {
        this.setStartPage(this.pageNum);
        this.setEndPage(this.pageNum);
        this.getText(this.document);
        return this.textList;
    }

    protected void processTextPosition(TextPosition text) {
        String textStr = text.toString();
        if (!textStr.matches("\\s")) {
            this.movingWords.append(textStr);
            int lenM = this.movingWords.length();
            int lenK = this.keyword.length();
            if (lenM >= lenK) {
                if (lenM > lenK) {
                    this.movingWords = new StringBuffer(this.movingWords.substring(lenM - lenK));
                }
                
                if (this.keyword.toString().contentEquals(this.movingWords)) {
                    KeyWordPosition keyWordPosition = new KeyWordPosition(this.pageNum, text.getX(), text.getPageHeight()-text.getY());
                    this.textList.add(keyWordPosition);
                }

            }
        }
    }
}
